import React, { PureComponent } from "react";
import {StyleSheet, View, Text, AppState, Dimensions} from "react-native";
import { connect } from "react-redux";
import { debounce } from "../../utils";
import { TYSdk } from 'tuya-panel-kit';
import { commonApi } from '@tuya/tuya-panel-api';
import { LineChart } from 'react-native-chart-kit';
import dpCodes from "../../config/dpCodes";
import Strings from "../../i18n";
import kColor from "../../config/kColor";

const {
  fishtank_temperature_type: fishtank_temperature_typeCode,
} = dpCodes;

class HomeTempView extends PureComponent {

  constructor(props) {
    super(props);

    this.state = {
      tempData: [0],// 初始化要赋值，否则折线图安卓会崩溃
      todayTemp: [0],
      yesterdayTemp: [0],
      timeArr: [],
      timeLabels: ['00:00', '06:00', '12:00', '18:00', '24:00'],
    };
  }

  componentDidMount() {


    const yesterday = getYesterdayDateString();
    this.getTempData(yesterday);
  }

  getTempData = ((date) => {

    commonApi.statApi
      // .getLogInSpecifiedTime({
      //   devId: TYSdk.devInfo.devId,
      //   dpIds: '104', // 多个DP
      //   offset: 0,
      //   limit: 24,
      //   startTime: '',
      //   endTime: '',
      //   sortType: 'ASC',
      // })
      .getDpResultByHour({
        devId: TYSdk.devInfo.devId,
        dpId: '104',
        date: date,
        auto: 1,
        type: 'avg',
        uid: '',
      })
      .then(response => {
        // const temps = Object.values(response).map(Number);
        const yesterdayTemp = Object.values(response).map(value => Math.round(parseFloat(value)));
        const time = Object.keys(response).map(key => key.slice(-2)+':00');
        console.log('昨天温度数据',yesterdayTemp);
        console.log('时间',time);

        this.setState({ yesterdayTemp: yesterdayTemp, timeArr: time });

        const today = getTodayDateString();
        this.getTempData1(today);

      })
      .catch();
  });

  getTempData1 = ((date) => {

    commonApi.statApi
      .getDpResultByHour({
        devId: TYSdk.devInfo.devId,
        dpId: '104',
        date: date,
        auto: 1,
        type: 'avg',
        uid: '',
      })
      .then(response => {
        // const temps = Object.values(response).map(Number);
        const todayTemp = Object.values(response).map(value => Math.round(parseFloat(value)));
        const time = Object.keys(response).map(key => key.slice(-2)+':00');
        console.log('今天温度数据',todayTemp);
        this.setState({ todayTemp: todayTemp });

        const { yesterdayTemp, timeArr } = this.state;
        const allTempData = yesterdayTemp.concat(todayTemp);
        let last24Elements = allTempData.splice(-25);

        let allTime = timeArr.concat(time);
        let last24Time = allTime.splice(-25);
        let timeLabels = [];
        console.log('last24Time', last24Time);
        if (last24Time.length < 2) {
          last24Elements = [0];
          timeLabels = ['00:00', '06:00', '12:00', '18:00', '24:00'];
        }else if (last24Time.length <= 5) {
          timeLabels = last24Time;
        }else if (last24Time.length <= 12) {
          const index = Math.round(last24Time.length / 2);
          timeLabels = [last24Time[0], last24Time[index], last24Time[last24Time.length - 1]];
        }else {
          const indexMid = Math.floor(last24Time.length / 2);// 向下取整
          // console.log('indexMid', indexMid);
          const index1 = Math.floor((last24Time.length - 1) /4);
          // console.log('index1', index1);
          const index2 = Math.floor((last24Time.length-1) * 3/4);
          // console.log('index2', index2);
          timeLabels = [last24Time[0], last24Time[index1], last24Time[indexMid], last24Time[index2], last24Time[last24Time.length - 1]];
        }
        console.log('timeLabels', timeLabels);
        console.log('last24Elements', last24Elements);
        this.setState({ tempData: last24Elements, timeLabels: timeLabels });

      })
      .catch();
  });

  render() {
    const { fishtank_temperature_type } = this.props;
    const { tempData, timeLabels } = this.state;

    const tempType = fishtank_temperature_type === 'celsius' ? "℃" : "℉";
    console.log('fishtank_temperature_type', fishtank_temperature_type);

    const data = {
      labels: timeLabels,//['00:00', '06:00', '12:00', '18:00', '24:00'],
      datasets: [{
        data: tempData,//[ 20, 12, 20 ],
        color: (opacity = 0.5) => `rgba(34, 168, 220, ${opacity})`, // 线条颜色
        strokeWidth: 3, // 线条宽度
      }]
    }

    const chartConfig = {
      backgroundColor: kColor.type === 'dark'?"#1a1a1a":"#f4f4f4",
      backgroundGradientFrom: kColor.type === 'dark'?"#1a1a1a":"#f4f4f4",
      backgroundGradientTo: kColor.type === 'dark'?"#1a1a1a":"#f4f4f4",
      color: (opacity = 1) => `rgba(179, 179, 179, ${opacity})`,// 标签和轴的颜色
      strokeWidth: 2, // optional, default 3
      decimalPlaces: 0, // 数字小数点位数
    }

    return (
      <View style={[styles.container, kColor.theme[kColor.type].homeCardBgColor]}>
        <Text style={[styles.topText, kColor.theme[kColor.type].titleColor]}>{Strings.formatValue('home_temp_history_title', tempType)}</Text>
        <View style={styles.chart}>
          {/* 图表 */}
          <LineChart
              data={data}
              chartConfig={chartConfig}
              width={Dimensions.get('window').width-20} // 根据需要设置宽度
              height={280}
              segments={5} // Y轴格数
              withDots={false}
              withVerticalLines={false} // 隐藏Y轴网格线
              bezier
              fromZero={true} // Y轴刻度从0开始，默认从最小值开始
              // yAxisInterval={20} // 设置Y轴的间隔为10
              // yAxisSuffix={'℃'} // Y轴坐标后缀
              style={{
                marginVertical: 10,
                marginRight: 20,
                backgroundColor: '#282828',
                // borderRadius: 16,
              }}
          />

        </View>
        <Text style={[styles.lightText, kColor.theme[kColor.type].subTitleColor]}>{Strings.home_temp_history_description}</Text>
      </View>
    );
  }
}

// 获取昨天的日期并将其格式化为yyyymmdd格式
function getYesterdayDateString() {
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  const year = yesterday.getFullYear();
  const month = ('0' + (yesterday.getMonth() + 1)).slice(-2); // 月份是从0开始的
  const day = ('0' + yesterday.getDate()).slice(-2);
  return `${year}${month}${day}`;
}

// 获取今天的日期并将其格式化为yyyymmdd格式
function getTodayDateString() {
  const today = new Date();
  const year = today.getFullYear();
  const month = (today.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
  const day = today.getDate().toString().padStart(2, '0');
  return `${year}${month}${day}`;
}

function maxMinusMin(arr) {
  const max = Math.max(...arr);
  const min = Math.min(...arr);
  return max - min;
}

const data1 = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [{
    data: [20, 45, 28, 80, 20, 35],
    color: (opacity = 1) => `rgba(134, 65, 244, ${opacity})`, // 指定单一颜色
    // 使用渐变色
    strokeCap: 'round',
    // 渐变色配置
    gradientColorFrom: '#8641FF',
    gradientColorTo: '#AD57FF',
    gradientDirection: 'top', // 渐变方向
    // 如果你想要一个渐变的填充而不是只有边缘颜色渐变，可以设置如下：
    fillShadow: true,
    shadowColor: 'rgba(134, 65, 244, 0.3)',
    shadowBlur: 8,
    shadowOffsetX: 0,
    shadowOffsetY: 0,
  }],
};

const chartConfig1 = {
  backgroundGradientFrom: '#ffffff',
  backgroundGradientTo: '#ffffff',
  decimalPlaces: 2, // 数据小数点后位数
  color: (opacity = 1) => `rgba(134, 65, 244, ${opacity})`,
  labelColor: () => `rgba(255, 255, 255, 0.3)`,
  propsForDots: {
    r: "3",
    strokeWidth: "2",
    stroke: "#ffa726",
  },
};

const styles = StyleSheet.create({
  container: {
    // width: '100%',
    height: 400,
    flex: 1,
    backgroundColor: '#fff',
    marginHorizontal: 10,
    marginTop: 10,
    marginRight: 10,
    borderRadius: 12,
  },
  topText: {
    marginTop: 20,
    marginStart: 30,
    height: 30,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#000',
  },
  lightText: {
    marginTop: 20,
    marginStart: 30,
    fontSize: 14,
    color: '#757575',
  },
  chart: {
    height: 280,
    // backgroundColor: '#ffffff',
  },
});

export default connect(({dpState}) => ({
  dpState,
  fishtank_temperature_type: dpState[fishtank_temperature_typeCode],
}))(HomeTempView);

